
module DrunkenMaster
  
  # Representation of html page built out of Element objects.
  class HtmlPage < Element
    attr_reader :body, :head, :title
    attr_accessor :doctype
    
    # Creates a page with standard XHTML 1.0 Strict DTD
    def initialize
      @doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
      super(:html,
        :xmlns => 'http://www.w3.org/1999/xhtml',
        'xml:lang' => 'en',
        :lang => 'en'
      )      
      build_html_skeleton      
    end
    
    # Adds <head> some metas, <body>.x..
    def build_html_skeleton
      @head = e :head
      @title = head.e :title,
        :innerHTML => 'DrunkenMaster application'
      @head.e :meta, 
        'http-equiv' => 'Content-Type',
        :content => "text/html; charset=UTF-8"
      @body = e :body      
    end
    
    # Adds css reference to page head.
    def link_css file
      expect_file file
      @linked ||= {}
      @linked[:css] ||= {}
      unless @linked[:css][file]
        e = 
        @head.e :link,
          :rel => 'stylesheet',
          :href => file,
          :type => 'text/css',
          :media => 'screen'
        @linked[:css][file] = true
      end
      e
    end
    
    # Adds js reference to page head.
    def link_js file
      expect_file file
      @linked ||= {}
      @linked[:js] ||= {}
      unless @linked[:js][file]
        e =
        @head.e :script,
          :type => 'text/javascript',
          :src => file,
          :innerHTML => ''
        @linked[:js][file] = true
      end
      e
    end
    
    # Renders whole page using body, head...
    def render
      [@doctype] + super()
    end
    
  private 
    
    def expect_file file
      raise 'No file given.' if file == '' || file.nil?
    end
    
  end
end